#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""
高级大模型增强模块

本模块提供了增强的大模型交互能力，支持复杂任务规划、多轮对话管理和外部API集成，
使系统能够处理更高级的指令如"点外卖"等复杂操作。
"""

import os
import json
import logging
import time
import threading
from typing import Dict, List, Tuple, Optional, Any, Callable

# 配置日志
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
logger = logging.getLogger(__name__)

class AdvancedLLMEnhancer:
    """高级大模型增强器，提供复杂任务处理能力"""
    
    def __init__(self):
        """初始化高级大模型增强器"""
        self.llm_interface = None
        self.session_history = {}
        self.api_integrations = {}
        self.task_templates = self._load_task_templates()
        self.thread_lock = threading.RLock()
        
        # 尝试导入并初始化大模型接口（使用模拟模式，避免下载依赖）
        self._init_llm_interface(simulate_mode=True)
        
        # 注册外部API集成
        self._register_default_api_integrations()
    
    def _init_simulated_model(self):
        """初始化模拟的大模型接口"""
        logging.info("使用模拟大模型接口")
        # 创建一个简单的模拟接口
        self.llm_interface = MockLLMInterface()
        self.has_local_model = False
        self.use_simulated_model = True
    
    def _init_llm_interface(self, simulate_mode=False):
        """初始化大模型接口
        
        Args:
            simulate_mode: 是否使用模拟模式，不实际加载模型
        """
        try:
            if simulate_mode:
                logging.info("使用模拟模式初始化大模型接口")
                self._init_simulated_model()
                return
            
            # 尝试导入现有的大模型接口模块
            if os.path.exists('llm_interface.py'):
                from llm_interface import LLMInterface
                self.llm_interface = LLMInterface()
                logger.info("大模型接口初始化成功")
            else:
                logger.warning("未找到llm_interface.py，使用模拟大模型接口")
                # 使用模拟接口作为后备
                self.llm_interface = MockLLMInterface()
        except Exception as e:
            logger.error(f"大模型接口初始化失败: {str(e)}")
            # 使用模拟接口作为后备
            self.llm_interface = MockLLMInterface()
    
    def _register_default_api_integrations(self):
        """注册默认的外部API集成"""
        # 注册外卖API集成
        self.api_integrations['food_delivery'] = FoodDeliveryAPIIntegration()
        # 注册电商平台API集成
        self.api_integrations['ecommerce'] = EcommerceAPIIntegration()
        # 注册浏览器控制API集成
        self.api_integrations['browser_control'] = BrowserControlAPIIntegration()
        # 注册系统操作API集成
        self.api_integrations['system_operations'] = SystemOperationsAPIIntegration()
    
    def _load_task_templates(self):
        """加载任务模板"""
        return {
            'food_delivery': {
                'prompt_template': """你是一个智能助手，帮助用户完成点外卖任务。
用户请求: {user_request}
需要完成的步骤:
1. 分析用户需求，确定餐厅、菜品、送餐地址等关键信息
2. 如果信息不足，向用户提问获取必要信息
3. 调用外卖API搜索餐厅和菜品
4. 帮助用户下单并跟踪订单状态
5. 总结整个过程

请根据当前对话历史和用户请求，生成下一步响应。""",
                'required_info': ['restaurant', 'dishes', 'address'],
                'api_calls': ['search_restaurants', 'view_menu', 'place_order', 'track_order']
            },
            'complex_browser_task': {
                'prompt_template': """你是一个智能浏览器控制器，帮助用户完成复杂的网页操作任务。
用户请求: {user_request}
需要完成的步骤:
1. 分析任务需求，确定需要访问的网站和执行的操作
2. 规划访问路径和操作顺序
3. 依次执行打开网站、导航、点击、输入等操作
4. 收集所需信息或完成指定任务
5. 向用户报告完成情况

请根据当前对话历史和用户请求，生成任务执行计划。""",
                'required_info': ['website', 'target_actions'],
                'api_calls': ['open_website', 'navigate', 'click_element', 'input_text', 'extract_info']
            },
            'workflow_automation': {
                'prompt_template': """你是一个工作流自动化助手，帮助用户完成一系列相关任务。
用户请求: {user_request}
需要完成的步骤:
1. 分析用户的工作流需求
2. 将复杂任务分解为可执行的子任务序列
3. 按顺序执行每个子任务
4. 根据执行结果调整后续步骤
5. 提供完整的执行报告

请根据当前对话历史和用户请求，生成工作流执行计划。""",
                'required_info': ['workflow_goal', 'available_resources'],
                'api_calls': ['execute_subtask', 'check_status', 'adjust_plan', 'summarize_results']
            }
        }
    
    def process_complex_command(self, user_request: str, session_id: str = 'default') -> str:
        """处理复杂命令，支持多轮对话和任务规划"""
        with self.thread_lock:
            # 确保会话历史存在
            if session_id not in self.session_history:
                self.session_history[session_id] = {
                    'conversations': [],
                    'current_task': None,
                    'task_progress': {},
                    'collected_info': {},
                    'created_at': time.time(),
                    'last_updated': time.time()
                }
            
            session = self.session_history[session_id]
            session['last_updated'] = time.time()
            session['conversations'].append({'role': 'user', 'content': user_request})
            
            try:
                # 任务类型识别和处理 - 增强特定场景处理
                # 调整优先级顺序，确保信息查询任务被优先识别
                # 特殊模式先判断 - "如何做"、"怎么做"等明确的查询模式
                if any(pattern in user_request for pattern in ["如何做", "怎么做", "如何制作", "制作方法"]):
                    logger.info("识别到任务类型: information_query")
                    result = self._process_information_query(user_request, session)
                elif self._is_information_query(user_request):
                    logger.info("识别到任务类型: information_query")
                    result = self._process_information_query(user_request, session)
                elif self._is_food_delivery_task(user_request):
                    task_type = 'food_delivery'
                    session['current_task'] = task_type
                    logger.info(f"识别到任务类型: {task_type}")
                    result = self._process_food_delivery_command(user_request, session)
                elif self._is_shopping_task(user_request):
                    task_type = 'shopping'
                    session['current_task'] = task_type
                    logger.info(f"识别到任务类型: {task_type}")
                    result = self._process_shopping_command(user_request, session)
                elif self._is_workflow_task(user_request):
                    task_type = 'workflow_automation'
                    session['current_task'] = task_type
                    logger.info(f"识别到任务类型: {task_type}")
                    result = "为了帮您设计工作流，我需要知道具体的流程步骤和自动化要求。请详细说明。"
                else:
                    # 如果当前有进行中的任务，继续执行
                    if session['current_task']:
                        if session['current_task'] == 'food_delivery':
                            result = self._process_food_delivery_command(user_request, session)
                        elif session['current_task'] == 'shopping':
                            result = self._process_shopping_command(user_request, session)
                        elif not self._is_task_complete(session):
                            # 其他类型任务继续执行
                            result = self._continue_task(session, user_request)
                        else:
                            # 任务已完成，开始新任务
                            task_type = self._analyze_task_type(user_request)
                            logger.info(f"识别到任务类型: {task_type}")
                            result = self._start_new_task(session, user_request, task_type)
                    else:
                        # 开始新任务
                        task_type = self._analyze_task_type(user_request)
                        logger.info(f"识别到任务类型: {task_type}")
                        result = self._start_new_task(session, user_request, task_type)
                
                # 记录当前任务状态
                session['current_task_type'] = task_type if 'task_type' in locals() else None
                
                session['conversations'].append({'role': 'assistant', 'content': result})
                return result
                
            except Exception as e:
                logger.error(f"处理复杂命令时出错: {str(e)}")
                error_response = f"处理命令时出现错误: {str(e)}"
                session['conversations'].append({'role': 'assistant', 'content': error_response})
                return error_response
                
    def _is_workflow_task(self, command: str) -> bool:
        """判断是否为工作流任务"""
        workflow_keywords = ["自动化", "流程", "工作流", "脚本", "计划", 
                           "安排", "设置", "定时", "提醒"]
        return any(keyword in command for keyword in workflow_keywords)
        
    def _is_information_query(self, command: str) -> bool:
        """判断是否为信息查询任务"""
        # 优先检查信息查询关键词，特别是那些明确的问题形式
        query_keywords = [
            "天气", "时间", "日期", "历史", "新闻", "百科", "是什么", "有什么", 
            "为什么", "怎么", "如何", "方法", "步骤", "攻略", "教程", 
            "什么是", "有哪些", "查询", "搜索", "查找", "了解", "了解一下", 
            "介绍", "说明", "含义", "意思", "定义", "概念", "原理", "原因", 
            "开放时间", "营业时间", "工作时间", "什么时候", "几点", "哪里有", "哪里", 
            "怎么走", "路线", "地址", "导航", "地图"
        ]
        
        # 先检查是否包含明确的信息查询模式
        question_patterns = ["如何做", "怎么做", "如何制作", "制作方法"]
        for pattern in question_patterns:
            if pattern in command and "订单" not in command and "下单" not in command:
                # 例如"如何做麻婆豆腐"应该被识别为信息查询，而不是外卖
                return True
        
        # 检查是否包含查询关键词
        for keyword in query_keywords:
            if keyword in command:
                # 确保不是外卖或购物相关的命令
                # 特殊处理：即使包含菜品名，"如何做XX"也应该被识别为信息查询
                if "如何做" in command or "怎么做" in command:
                    return True
                # 正常的外卖和购物判断
                if not (self._is_food_delivery_task(command) or self._is_shopping_task(command)):
                    return True
        return False
        
    def _process_information_query(self, command: str, session: dict) -> str:
        """处理信息查询请求"""
        import datetime
        
        # 天气查询
        if any(keyword in command for keyword in ['天气', '气温', '温度']):
            # 提取城市
            cities = ['北京', '上海', '广州', '深圳', '杭州', '成都', '武汉', '西安', '南京', '重庆']
            city = None
            for c in cities:
                if c in command:
                    city = c
                    break
            
            if city:
                return f"{city}当前天气信息模拟回复：今天天气晴朗，温度适宜。"
            else:
                return "请问您想查询哪个城市的天气？"
        
        # 开放时间查询 - 移到时间查询之前，提高优先级
        if any(keyword in command for keyword in ['开放时间', '营业时间', '几点开门', '几点关门']):
            if '故宫' in command or '故宫博物院' in command:
                return "故宫博物院的开放时间通常为周二至周日8:30-17:00，周一闭馆（法定节假日除外）。"
            elif '博物馆' in command:
                return "大多数博物馆的开放时间为周二至周日9:00-17:00，周一闭馆（法定节假日除外）。"
            else:
                return "具体开放时间取决于具体场所，建议查询官方网站或拨打电话咨询。"
        
        # 时间查询
        if any(keyword in command for keyword in ['时间', '几点', '现在']):
            current_time = datetime.datetime.now().strftime("%H:%M")
            return f"现在是{current_time}。"
        
        # 日期查询
        if any(keyword in command for keyword in ['日期', '几号', '今天']):
            current_date = datetime.datetime.now().strftime("%Y年%m月%d日")
            return f"今天是{current_date}。"
        
        # 制作方法查询
        elif any(pattern in command for pattern in ["如何做", "怎么做", "制作方法"]):
            # 提取菜品或物品名称
            food_patterns = ["麻婆豆腐", "宫保鸡丁", "红烧肉", "鱼香肉丝", "糖醋排骨"]
            food = ""
            for pattern in food_patterns:
                if pattern in command:
                    food = pattern
                    break
            
            if food:
                return f"制作{food}的基本步骤：1. 准备食材；2. 切配；3. 炒制；4. 调味；5. 出锅装盘。详细做法建议参考专业食谱。"
            else:
                return "制作方法需要根据具体菜品或物品而定。请提供具体的菜品或物品名称，我可以为您提供基本制作步骤。"
        
        # 地址/路线查询
        elif any(keyword in command for keyword in ['位置', '在哪里', '地址', '路线', '怎么走']):
            return "关于地址和路线信息，建议您使用地图导航应用查询最新、最准确的信息。"
        
        # 菜谱查询 - 保留原有的菜谱查询逻辑作为补充
        elif any(keyword in command for keyword in ['做法', '食谱', '菜谱']):
            # 简单的菜谱匹配
            if '麻婆豆腐' in command:
                return "麻婆豆腐的做法：1.准备豆腐、肉末、豆瓣酱、葱姜蒜等材料；2.豆腐切块焯水；3.热锅冷油炒香肉末和豆瓣酱；4.加入豆腐和适量水炖煮；5.勾芡调味即可。"
            elif '宫保鸡丁' in command:
                return "宫保鸡丁的做法：1.鸡肉切丁用盐、淀粉腌制；2.花生米油炸备用；3.热锅冷油炒香葱姜蒜和干辣椒；4.加入鸡丁翻炒；5.加入调料和花生米炒匀即可。"
            else:
                return "请告诉我您想学习哪道菜的做法？"
        
        # 通用回复
        return "这是一个信息查询请求，对于更详细的信息，建议查阅专业资料或咨询相关领域的专家。"
                
    def _is_food_delivery_task(self, command: str) -> bool:
        """判断是否为外卖任务"""
        food_keywords = ["点外卖", "外卖", "美团", "饿了么", "订餐", "下单", 
                        "吃什么", "餐厅", "饭店", "川菜", "火锅", "披萨", 
                        "汉堡", "宫保鸡丁", "麻婆豆腐", "米饭", "送餐"]
        return any(keyword in command for keyword in food_keywords)
        
    def _is_shopping_task(self, command: str) -> bool:
        """判断是否为购物任务"""
        shopping_keywords = ["淘宝", "京东", "购物", "搜索", "买", "下单", 
                           "价格", "推荐", "产品", "商品", "衬衫", "手机", 
                           "鞋子", "外套", "智能", "家居"]
        return any(keyword in command for keyword in shopping_keywords)
        
    def _process_food_delivery_command(self, command: str, session: dict) -> str:
        """处理外卖命令"""
        # 提取会话信息
        collected_info = session.get('collected_info', {})
        dishes = collected_info.get('dishes', [])
        
        # 菜品提取逻辑增强，避免重复添加
        dish_patterns = [
            ("麻婆豆腐", "麻婆豆腐"),
            ("米饭", "米饭"),
            ("宫保鸡丁", "宫保鸡丁"),
            ("火锅", "火锅"),
            ("披萨", "披萨"),
            ("汉堡", "汉堡")
        ]
        
        # 提取菜品，避免重复
        for pattern, dish_name in dish_patterns:
            if pattern in command and dish_name not in dishes:
                dishes.append(dish_name)
        
        # 菜系提取
        if "川菜" in command:
            collected_info['cuisine'] = "川菜"
        
        # 口味提取
        if "不辣" in command:
            collected_info['spicy_level'] = "不辣"
        elif "微辣" in command:
            collected_info['spicy_level'] = "微辣"
        elif "特辣" in command:
            collected_info['spicy_level'] = "特辣"
        
        # 检查是否有地址信息
        address_keywords = ["地址", "送到", "配送", "位置", "小区", "大厦", "街道"]
        for keyword in address_keywords:
            if keyword in command:
                collected_info['has_address'] = True
                # 尝试提取地址
                address_start = command.find(keyword)
                address_end = command.find('，', address_start) if '，' in command[address_start:] else len(command)
                collected_info['address'] = command[address_start:address_end].replace(keyword, '').strip()
                break
        
        # 检查是否包含订单确认关键词
        if any(keyword in command.lower() for keyword in ['确认订单', '确认', '下单', '提交']):
            if dishes and collected_info.get('has_address'):
                dishes_str = "、".join(dishes)
                address = collected_info.get('address')
                response = f"已为您确认订单，菜品：{dishes_str}，送餐地址：{address}"
                if 'spicy_level' in collected_info:
                    response += f"，口味要求：{collected_info['spicy_level']}"
                response += "。订单已提交，预计30分钟内送达。"
                # 记录订单状态
                collected_info['order_status'] = 'confirmed'
                return response
            elif not dishes:
                return "您还没有选择任何菜品，请先告诉我您想点什么。"
            else:
                return "请先提供送餐地址，然后再确认订单。"
        
        # 处理完整的下单指令
        if "下单" in command and dishes and collected_info.get('has_address'):
            dishes_str = "、".join(dishes)
            delivery_time = "30分钟左右"
            return f"已成功下单！您点的{dishes_str}将在{delivery_time}送达您的地址。"
        
        # 更新会话信息
        collected_info['dishes'] = dishes
        session['collected_info'] = collected_info
        
        # 检查是否缺少必要信息
        missing_info = []
        if not collected_info.get('has_address'):
            missing_info.append("送餐地址")
        if not dishes:
            missing_info.append("想要点的菜品")
        
        if missing_info:
            if dishes:
                dishes_str = "、".join(dishes)
                if len(missing_info) == 1:
                    return f"我已记录您要点的菜品：{dishes_str}。还需要您提供{missing_info[0]}才能为您下单。"
                else:
                    return f"我已记录您要点的菜品：{dishes_str}。还需要您提供{', 和'.join(missing_info)}才能为您下单。"
            else:
                return f"为了帮您点外卖，我需要知道{', 和'.join(missing_info)}。"
        else:
            # 提示用户确认订单
            dishes_str = "、".join(dishes)
            response = f"我已记录您要点的菜品：{dishes_str}，送餐地址：{collected_info.get('address')}"
            if 'spicy_level' in collected_info:
                response += f"，口味要求：{collected_info['spicy_level']}"
            response += "。请说'确认订单'来完成下单。"
            return response
            
    def _process_shopping_command(self, command: str, session: dict) -> str:
        """处理购物命令"""
        # 提取会话信息
        collected_info = session.get('collected_info', {})
        
        # 初始化购物车
        if 'shopping_cart' not in collected_info:
            collected_info['shopping_cart'] = []
        
        # 提取商品信息
        product_name = ""
        if "衬衫" in command:
            product_name = "衬衫"
            if "男士" in command:
                product_name = "男士衬衫"
            if "长袖" in command:
                product_name = product_name.replace("衬衫", "长袖衬衫")
        elif "手机" in command:
            product_name = "手机"
        elif "运动鞋" in command:
            product_name = "运动鞋"
        
        # 添加到购物车
        if product_name:
            # 检查是否已存在相同商品
            existing_product = None
            for p in collected_info['shopping_cart']:
                if p.get('name') == product_name:
                    existing_product = p
                    break
            
            if not existing_product:
                collected_info['shopping_cart'].append({'name': product_name})
        
        # 提取价格信息
        import re
        price_match = re.search(r'\d+元', command)
        if price_match:
            collected_info['price_range'] = price_match.group()
        
        # 检查是否包含确认购买关键词
        if any(keyword in command.lower() for keyword in ['确认', '购买', '下单', '结账', '确认订单']):
            if collected_info['shopping_cart']:
                cart_summary = [item.get('name', '') for item in collected_info['shopping_cart']]
                cart_str = '、'.join(cart_summary)
                collected_info['order_status'] = 'confirmed'
                return f"已为您确认订单，商品：{cart_str}。订单已提交，请等待发货。"
            else:
                return "您的购物车是空的，请先添加商品。"
        
        # 更新会话信息
        session['collected_info'] = collected_info
        
        # 生成响应
        if collected_info.get('product_type') or collected_info['shopping_cart']:
            if collected_info['shopping_cart']:
                cart_summary = [item.get('name', '') for item in collected_info['shopping_cart']]
                cart_str = '、'.join(cart_summary)
                return f"已将商品添加到购物车：{cart_str}。您可以继续添加商品或输入'确认购买'完成订单。"
            else:
                response = f"我已为您搜索{collected_info['product_type']}"
                if collected_info.get('price_range'):
                    response += f"，价格在{collected_info['price_range']}左右"
                response += "。以下是搜索结果：\n1. 推荐产品A - 品质优良，好评率高\n2. 推荐产品B - 性价比高\n3. 推荐产品C - 款式新颖\n您想了解哪一款的详细信息？"
                return response
        else:
            return "为了帮您购物，我需要知道您具体想买什么商品。请提供商品名称和您的需求。"
    
    def _analyze_task_type(self, user_request: str) -> str:
        """分析任务类型"""
        # 简单的任务类型识别逻辑
        if any(keyword in user_request for keyword in ['外卖', '订餐', '吃饭', '餐厅', '点餐']):
            return 'food_delivery'
        elif any(keyword in user_request for keyword in ['浏览器', '网页', '网站', '搜索', '访问']):
            return 'complex_browser_task'
        elif any(keyword in user_request for keyword in ['流程', '自动化', '一系列', '依次', '步骤']):
            return 'workflow_automation'
        else:
            return 'general'
    
    def _start_new_task(self, session: Dict, user_request: str, task_type: str) -> str:
        """开始新任务"""
        if task_type in self.task_templates:
            template = self.task_templates[task_type]
            session['current_task'] = task_type
            session['task_progress'] = {'total_steps': len(template['required_info']), 'completed_steps': 0}
            
            # 使用大模型分析请求并提取信息
            prompt = template['prompt_template'].format(user_request=user_request)
            llm_response = self._call_llm(prompt, session)
            
            # 解析大模型响应
            parsed_result = self._parse_llm_response(llm_response, task_type)
            
            # 检查是否需要更多信息
            missing_info = self._check_missing_info(parsed_result, template['required_info'])
            if missing_info:
                # 向用户请求缺失信息
                question = self._generate_information_request(missing_info, user_request)
                session['collected_info'] = parsed_result.get('collected_info', {})
                return question
            else:
                # 开始执行任务
                session['collected_info'] = parsed_result.get('collected_info', {})
                return self._execute_task_step(session, 0)
        else:
            # 通用任务处理
            return self._handle_general_task(session, user_request)
    
    def _continue_task(self, session: Dict, user_response: str) -> str:
        """继续执行现有任务"""
        task_type = session['current_task']
        
        # 将用户响应添加到收集的信息中
        template = self.task_templates.get(task_type, {})
        required_info = template.get('required_info', [])
        
        # 使用大模型分析用户响应并更新收集的信息
        prompt = f"""用户提供了以下信息作为回应: {user_response}
请从这个回应中提取与{', '.join(required_info)}相关的信息，并以JSON格式返回。"""
        llm_response = self._call_llm(prompt, session)
        
        try:
            # 尝试解析JSON响应
            extracted_info = json.loads(llm_response)
            # 更新收集的信息
            session['collected_info'].update(extracted_info)
        except json.JSONDecodeError:
            # 如果不是JSON，让大模型提取关键信息
            logger.warning("无法解析大模型的JSON响应，尝试直接提取信息")
            session['collected_info']['additional_info'] = user_response
        
        # 检查是否还有缺失信息
        missing_info = self._check_missing_info(session['collected_info'], required_info)
        if missing_info:
            # 继续请求缺失信息
            return self._generate_information_request(missing_info, user_response)
        else:
            # 开始执行任务
            return self._execute_task_step(session, 0)
    
    def _execute_task_step(self, session: Dict, step_index: int) -> str:
        """执行任务的特定步骤"""
        task_type = session['current_task']
        template = self.task_templates.get(task_type, {})
        api_calls = template.get('api_calls', [])
        
        if step_index >= len(api_calls):
            # 任务完成
            session['task_progress']['completed_steps'] = len(api_calls)
            return self._summarize_task_completion(session)
        
        current_api = api_calls[step_index]
        logger.info(f"执行任务步骤 {step_index + 1}/{len(api_calls)}: {current_api}")
        
        try:
            # 根据任务类型和API调用执行相应操作
            if task_type == 'food_delivery' and task_type in self.api_integrations:
                api = self.api_integrations[task_type]
                result = self._execute_food_delivery_step(api, current_api, session['collected_info'])
            elif task_type == 'complex_browser_task' and task_type in self.api_integrations:
                api = self.api_integrations[task_type]
                result = self._execute_browser_step(api, current_api, session['collected_info'])
            elif task_type == 'workflow_automation' and task_type in self.api_integrations:
                api = self.api_integrations[task_type]
                result = self._execute_workflow_step(api, current_api, session['collected_info'])
            else:
                result = f"正在模拟执行 {current_api} 操作..."
            
            # 更新进度
            session['task_progress']['current_step'] = step_index + 1
            session['task_progress']['last_action'] = current_api
            
            # 继续执行下一步或总结结果
            if 'error' not in result.lower():
                return self._execute_task_step(session, step_index + 1)
            else:
                return f"执行步骤 {current_api} 时出错: {result}\n任务已停止。"
                
        except Exception as e:
            logger.error(f"执行任务步骤时出错: {str(e)}")
            return f"执行步骤时出现错误: {str(e)}\n任务已停止。"
    
    def _execute_food_delivery_step(self, api: Any, step: str, info: Dict) -> str:
        """执行外卖任务步骤"""
        if step == 'search_restaurants':
            return api.search_restaurants(info.get('address', ''))
        elif step == 'view_menu':
            return api.view_menu(info.get('restaurant', ''))
        elif step == 'place_order':
            return api.place_order(info)
        elif step == 'track_order':
            order_id = info.get('order_id', '')
            return api.track_order(order_id) if order_id else "订单ID缺失"
        else:
            return f"未知的外卖任务步骤: {step}"
    
    def _execute_browser_step(self, api: Any, step: str, info: Dict) -> str:
        """执行浏览器任务步骤"""
        if step == 'open_website':
            return api.open_website(info.get('website', ''))
        elif step == 'navigate':
            return api.navigate(info.get('navigation_path', []))
        elif step == 'click_element':
            return api.click_element(info.get('target_element', ''))
        elif step == 'input_text':
            return api.input_text(info.get('input_field', ''), info.get('input_text', ''))
        elif step == 'extract_info':
            return api.extract_info(info.get('info_to_extract', ''))
        else:
            return f"未知的浏览器任务步骤: {step}"
    
    def _execute_workflow_step(self, api: Any, step: str, info: Dict) -> str:
        """执行工作流任务步骤"""
        if step == 'execute_subtask':
            return api.execute_subtask(info.get('current_subtask', ''))
        elif step == 'check_status':
            return api.check_status()
        elif step == 'adjust_plan':
            return api.adjust_plan(info.get('status', {}))
        elif step == 'summarize_results':
            return api.summarize_results()
        else:
            return f"未知的工作流任务步骤: {step}"
    
    def _call_llm(self, prompt: str, session: Dict) -> str:
        """调用大模型"""
        try:
            # 优先尝试使用模型管理器
            try:
                from model_manager import get_model_manager
                model_manager = get_model_manager()
                
                # 构建对话历史
                conversations = session.get('conversations', [])
                
                # 使用模型管理器生成响应
                response = model_manager.generate(
                    prompt=prompt,
                    provider="auto",  # 自动选择可用的模型提供商
                    system_prompt="你是一个智能助手，专门用于处理和执行任务。",
                    max_tokens=1024,
                    temperature=0.7
                )
                
                return response
            except ImportError:
                # 如果无法导入模型管理器，回退到原来的方式
                logger.warning("无法导入模型管理器，回退到原始调用方式")
                if self.llm_interface and hasattr(self.llm_interface, 'generate_response'):
                    # 构建对话历史
                    conversations = session.get('conversations', [])
                    return self.llm_interface.generate_response(prompt, conversations)
                else:
                    # 使用模拟响应
                    return self._generate_mock_response(prompt)
        except Exception as e:
            logger.error(f"调用大模型时出错: {str(e)}")
            return self._generate_mock_response(prompt)
    
    def _generate_mock_response(self, prompt: str) -> str:
        """生成模拟响应"""
        # 简单的模拟响应逻辑
        if '外卖' in prompt:
            return json.dumps({
                'task_type': 'food_delivery',
                'analyzed_request': prompt,
                'collected_info': {},
                'missing_info': ['restaurant', 'dishes', 'address'],
                'recommended_action': 'ask_user'
            }, ensure_ascii=False)
        elif '浏览器' in prompt:
            return json.dumps({
                'task_type': 'complex_browser_task',
                'analyzed_request': prompt,
                'collected_info': {},
                'missing_info': ['website', 'target_actions'],
                'recommended_action': 'ask_user'
            }, ensure_ascii=False)
        else:
            return "我需要更多信息来执行这个任务。"
    
    def _parse_llm_response(self, response: str, task_type: str) -> Dict:
        """解析大模型响应"""
        try:
            # 尝试解析JSON格式
            return json.loads(response)
        except json.JSONDecodeError:
            # 如果不是JSON，返回文本响应
            return {
                'analyzed_request': response,
                'collected_info': {},
                'missing_info': self.task_templates.get(task_type, {}).get('required_info', []),
                'recommended_action': 'ask_user'
            }
    
    def _check_missing_info(self, collected_info: Dict, required_info: List) -> List[str]:
        """检查缺失的必要信息"""
        missing = []
        for info in required_info:
            if info not in collected_info or not collected_info[info]:
                missing.append(info)
        return missing
    
    def _generate_information_request(self, missing_info: List[str], user_request: str) -> str:
        """生成信息请求"""
        info_map = {
            'restaurant': '餐厅名称',
            'dishes': '想要点的菜品',
            'address': '送餐地址',
            'website': '要访问的网站',
            'target_actions': '需要执行的操作',
            'workflow_goal': '工作流目标',
            'available_resources': '可用资源'
        }
        
        missing_names = [info_map.get(info, info) for info in missing_info]
        
        if len(missing_names) == 1:
            return f"为了帮您完成任务，我需要知道{missing_names[0]}。请提供这一信息。"
        else:
            return f"为了帮您完成任务，我需要知道以下信息：{', '.join(missing_names)}。请提供这些信息。"
    
    def _handle_general_task(self, session: Dict, user_request: str) -> str:
        """处理通用任务"""
        # 使用大模型处理通用请求
        prompt = f"""用户请求: {user_request}
请提供一个详细的回应，帮助用户完成请求或回答问题。"""
        return self._call_llm(prompt, session)
    
    def _is_task_complete(self, session: Dict) -> bool:
        """检查任务是否完成"""
        progress = session.get('task_progress', {})
        return progress.get('completed_steps', 0) >= progress.get('total_steps', 0)
    
    def _summarize_task_completion(self, session: Dict) -> str:
        """总结任务完成情况"""
        task_type = session['current_task']
        collected_info = session['collected_info']
        
        summaries = {
            'food_delivery': f"外卖订单已完成！\n\n餐厅: {collected_info.get('restaurant', '未指定')}\n" \
                            f"菜品: {collected_info.get('dishes', '未指定')}\n" \
                            f"送餐地址: {collected_info.get('address', '未指定')}\n" \
                            f"订单号: {collected_info.get('order_id', '未生成')}\n" \
                            f"预计送达时间: {collected_info.get('estimated_delivery_time', '未确定')}",
            'complex_browser_task': f"浏览器任务已完成！\n\n访问网站: {collected_info.get('website', '未指定')}\n" \
                                  f"执行的操作: {', '.join(collected_info.get('target_actions', []))}\n" \
                                  f"获取的信息: {collected_info.get('extracted_info', '无')}",
            'workflow_automation': f"工作流任务已完成！\n\n目标: {collected_info.get('workflow_goal', '未指定')}\n" \
                                 f"完成的子任务: {', '.join(collected_info.get('completed_subtasks', []))}\n" \
                                 f"结果: {collected_info.get('workflow_results', '无')}"
        }
        
        # 重置任务状态
        session['current_task'] = None
        session['task_progress'] = {}
        
        return summaries.get(task_type, "任务已完成！") + "\n\n您还有其他需要帮助的吗？"
    
    def get_session_info(self, session_id: str) -> Optional[Dict]:
        """获取会话信息"""
        with self.thread_lock:
            return self.session_history.get(session_id)
    
    def clear_session(self, session_id: str) -> bool:
        """清除会话信息"""
        with self.thread_lock:
            if session_id in self.session_history:
                del self.session_history[session_id]
                return True
            return False
            
    def process_command(self, command_text: str) -> Dict[str, Any]:
        """处理用户命令
        
        Args:
            command_text: 用户命令文本
            
        Returns:
            包含处理结果的字典，可能包含need_more_info和question（需要更多信息时）或response（处理结果）
        """
        with self.thread_lock:
            try:
                logging.info(f"高级增强器处理命令: {command_text}")
                
                # 默认使用default会话
                session_id = "default"
                
                # 确保会话历史存在
                if session_id not in self.session_history:
                    self.session_history[session_id] = {
                        'conversations': [],
                        'current_task': None,
                        'task_progress': {},
                        'collected_info': {},
                        'created_at': time.time(),
                        'last_updated': time.time()
                    }
                
                session = self.session_history[session_id]
                session['last_updated'] = time.time()
                
                # 调用已有的复杂命令处理方法
                response = self.process_complex_command(command_text, session_id)
                
                # 检查是否需要更多信息
                if any(keyword in response.lower() for keyword in ["需要", "请提供", "缺少", "什么", "哪个", "哪里"]):
                    return {
                        "need_more_info": True,
                        "question": response
                    }
                else:
                    return {
                        "response": response
                    }
                    
            except Exception as e:
                logging.error(f"处理命令时出错: {str(e)}")
                return {
                    "response": "抱歉，处理您的请求时出现错误。请稍后再试。"
                }

class MockLLMInterface:
    """模拟大模型接口，用于在没有真实大模型时提供功能"""
    
    def __init__(self):
        self.name = "Mock LLM Interface"
        logger.info("使用模拟大模型接口")
    
    def generate_response(self, prompt: str, conversations: List = None) -> str:
        """生成模拟响应"""
        # 简单的模式匹配逻辑来生成响应
        if '外卖' in prompt:
            return json.dumps({
                'task_type': 'food_delivery',
                'analyzed_request': prompt,
                'collected_info': {},
                'missing_info': ['restaurant', 'dishes', 'address'],
                'recommended_action': 'ask_user'
            }, ensure_ascii=False)
        elif '浏览器' in prompt:
            return json.dumps({
                'task_type': 'complex_browser_task',
                'analyzed_request': prompt,
                'collected_info': {},
                'missing_info': ['website', 'target_actions'],
                'recommended_action': 'ask_user'
            }, ensure_ascii=False)
        elif '工作流' in prompt:
            return json.dumps({
                'task_type': 'workflow_automation',
                'analyzed_request': prompt,
                'collected_info': {},
                'missing_info': ['workflow_goal', 'available_resources'],
                'recommended_action': 'ask_user'
            }, ensure_ascii=False)
        elif '信息' in prompt and '提取' in prompt:
            # 模拟从用户回复中提取信息
            if '餐厅' in prompt:
                return json.dumps({'restaurant': '麦当劳'})
            elif '菜品' in prompt:
                return json.dumps({'dishes': '巨无霸套餐'})
            elif '地址' in prompt:
                return json.dumps({'address': '北京市朝阳区某某街道123号'})
            else:
                return json.dumps({})
        else:
            return "我是一个模拟的大模型接口，正在努力理解您的请求..."

# API集成类
class FoodDeliveryAPIIntegration:
    """外卖API集成"""
    
    def __init__(self):
        self.name = "Food Delivery API"
        self.available_restaurants = ['麦当劳', '肯德基', '必胜客', '星巴克']
        self.current_order_id = None
    
    def search_restaurants(self, address: str) -> str:
        """搜索附近餐厅"""
        if not address:
            return "错误: 地址不能为空"
        return f"已在{address}附近找到以下餐厅: {', '.join(self.available_restaurants)}"
    
    def view_menu(self, restaurant: str) -> str:
        """查看餐厅菜单"""
        if restaurant in self.available_restaurants:
            menus = {
                '麦当劳': '巨无霸套餐, 麦辣鸡腿堡, 麦乐鸡, 薯条, 可乐',
                '肯德基': '原味鸡, 香辣鸡腿堡, 薯条, 可乐, 蛋挞',
                '必胜客': '超级至尊披萨, 海鲜披萨, 意面, 沙拉, 饮料',
                '星巴克': '拿铁, 卡布奇诺, 美式咖啡, 蛋糕, 三明治'
            }
            return f"{restaurant}菜单: {menus[restaurant]}"
        else:
            return f"错误: 餐厅{restaurant}不可用"
    
    def place_order(self, order_info: Dict) -> str:
        """下单"""
        restaurant = order_info.get('restaurant', '')
        dishes = order_info.get('dishes', '')
        address = order_info.get('address', '')
        
        if not all([restaurant, dishes, address]):
            return "错误: 订单信息不完整"
        
        # 生成模拟订单号
        import random
        self.current_order_id = f"ORDER-{random.randint(1000, 9999)}"
        order_info['order_id'] = self.current_order_id
        order_info['estimated_delivery_time'] = "30-45分钟"
        
        return f"订单已成功提交！订单号: {self.current_order_id}, 预计送达时间: 30-45分钟"
    
    def track_order(self, order_id: str) -> str:
        """跟踪订单状态"""
        if order_id == self.current_order_id:
            return "您的订单正在配送中，预计15分钟后送达"
        else:
            return "未找到指定订单"

class EcommerceAPIIntegration:
    """电商平台API集成"""
    
    def __init__(self):
        self.name = "E-commerce API"
    
    def search_products(self, query: str) -> str:
        """搜索商品"""
        return f"搜索到关于'{query}'的商品列表"
    
    def add_to_cart(self, product_id: str, quantity: int = 1) -> str:
        """添加到购物车"""
        return f"已将商品 {product_id} 添加到购物车，数量: {quantity}"
    
    def checkout(self, payment_info: Dict) -> str:
        """结账"""
        return "订单已提交，等待支付确认"

class BrowserControlAPIIntegration:
    """浏览器控制API集成"""
    
    def __init__(self):
        self.name = "Browser Control API"
        self.current_url = None
    
    def open_website(self, url: str) -> str:
        """打开网站"""
        self.current_url = url
        return f"已打开网站: {url}"
    
    def navigate(self, path: List[str]) -> str:
        """导航到指定路径"""
        return f"已导航至: {', '.join(path)}"
    
    def click_element(self, element_selector: str) -> str:
        """点击元素"""
        return f"已点击元素: {element_selector}"
    
    def input_text(self, field_selector: str, text: str) -> str:
        """输入文本"""
        return f"已在{field_selector}中输入: {text}"
    
    def extract_info(self, info_type: str) -> str:
        """提取信息"""
        return f"已提取{info_type}信息"

class SystemOperationsAPIIntegration:
    """系统操作API集成"""
    
    def __init__(self):
        self.name = "System Operations API"
    
    def execute_command(self, command: str) -> str:
        """执行系统命令"""
        return f"已执行命令: {command}"
    
    def get_system_info(self) -> str:
        """获取系统信息"""
        return "操作系统信息，硬件状态等"
    
    def monitor_process(self, process_name: str) -> str:
        """监控进程"""
        return f"已开始监控进程: {process_name}"

# 演示代码
if __name__ == "__main__":
    print("高级大模型增强模块演示")
    print("=" * 50)
    
    enhancer = AdvancedLLMEnhancer()
    
    # 演示会话
    session_id = "demo_session"
    
    # 演示外卖任务
    print("\n=== 外卖任务演示 ===")
    print(enhancer.process_complex_command("我想吃外卖", session_id))
    print(enhancer.process_complex_command("我想吃麦当劳的巨无霸套餐，送到北京市朝阳区某某街道123号", session_id))
    
    # 演示浏览器任务
    print("\n=== 浏览器任务演示 ===")
    print(enhancer.process_complex_command("帮我在网上查一些信息", "browser_session"))
    print(enhancer.process_complex_command("我想访问百度，搜索Python教程", "browser_session"))
    
    # 演示工作流任务
    print("\n=== 工作流任务演示 ===")
    print(enhancer.process_complex_command("帮我设计一个自动化工作流", "workflow_session"))
    print(enhancer.process_complex_command("每天早上9点自动查看邮件，然后整理待办事项", "workflow_session"))